<?php

namespace App\Service;

use App\Models\Order\GoodsOrder;
use EasyWeChat\Pay\Application;

class OrderService
{
    public function refund($orderId, $userId, $refundReason)
    {
        $goodsOrder = GoodsOrder::find($orderId);
        $orderSamples = $goodsOrder->samples;
        foreach ($orderSamples as &$orderSample) {
            if ($orderSample->status > 2) {
                return 'order.order_not_refund';
            }
        }
        $config = config('wechatpay');
        $app = new Application($config);
        $response = $app->getClient()->postJson("v3/refund/domestic/refunds", [
            "out_trade_no" => $goodsOrder->order_no,
            "out_refund_no" => $goodsOrder->order_no,
            "reason" => $refundReason,
            "notify_url" => url('api/v1/mini/payment_notify'),
            "funds_account" => "AVAILABLE",
            "amount" => [
                "refund" => intval($goodsOrder->final_price * 100),
                "total" => intval($goodsOrder->final_price * 100),
                "currency" => "CNY"
            ],
        ]);
        $refundResp = $response->toArray(false);
        if (!@$refundResp['refund_id']) {
//            Log::debug('退款失败', $refundResp);
            return 'order.order_not_refund_success';
        }
        $goodsOrder->refund_id = $refundResp['refund_id'];
        $goodsOrder->refund_reason = $refundReason;
        $goodsOrder->refund_operator_id = $userId;
        $goodsOrder->refunds_at = now();
        $goodsOrder->payment_status = 3;
        $goodsOrder->save();
        return null;
    }
}
